import random
from exit import db
from datetime import date, datetime, timedelta
from utils import restful, common_util
from apps.common.models import *
from apps.mall.models import *
from apps.mall.models_v2 import *
from decimal import Decimal
from apps.api.models import User, UserRecord
from flask import g
import string
from sqlalchemy import func


def user_extend_status_str(user_status):
    if user_status == 0:
        status_str = '普通用户'
    elif user_status == 1:
        status_str = '服务中心'
    else:
        status_str = '供货商'
    return status_str


def search_create_user_extend(goods_id, user_id, create_status, user_status=0):   # 查询创建用户身份
    user_extend = UserExtend2.query.filter_by(goods_id=goods_id, user_id=user_id).first()
    data_dict = dict()
    if user_extend is None:
        if create_status == 1:
            UserExtend2.insert_record(goods_id=goods_id, user_id=user_id, user_status=user_status)
        user_status = user_status
        data_dict['goods_id'] = goods_id
        data_dict['user_id'] = user_id
        data_dict['s_coupon_num'] = 0
        data_dict['user_status'] = user_status
    else:
        data_dict = user_extend.user_extend2_json()
    data_dict['user_status_str'] = user_extend_status_str(data_dict['user_status'])
    return data_dict


def lock_query(table, filters, read=False, nowait=False):
    try:
        result = db.session.query(table).filter(*filters).with_for_update(read=read, nowait=nowait).first()
        return result
    except:
        return None


def compute_release(total_price, total_num, ratio, low_price, high_price):
    print(total_price, total_num, ratio, low_price, high_price)
    average_price = int(total_price * ratio / total_num)
    # 平均价必须是价格区间内
    if average_price < low_price or average_price > high_price or total_num <= 0:
        print('平均价不在范围内', average_price)
        return None

    # 计算出平均价距离边界的距离
    min_range = int(min(average_price - low_price, high_price - average_price))
    # 如果边界为0，直接返回{平均值：数量}  400:1, 200:1
    if min_range == 0:
        return {average_price: total_num}

    # 根据距离和平均价，得出所有可用的价格范围列表
    price_range = list(range(average_price - min_range, average_price + min_range + 1))

    price_dict = dict()
    added_num = total_num % len(price_range)  # 额外的数量
    base_num = int(total_num / len(price_range))

    if base_num > 0:
        for i in price_range:
            price_dict[i] = base_num

    if added_num == 0:
        added_num_price_list = []
    elif added_num == 1:
        # 如果是1的特殊数字，直接就是平均价
        added_num_price_list = [average_price]
    elif added_num == 2:
        # 如果是2的特殊数字，分别分布在两端
        added_num_price_list = [price_range[0], price_range[-1]]
    else:
        # 计算相隔多少分配1个
        max_times = int(int(len(price_range) / 2) / int(added_num / 2))
        added_num_price_list = [average_price]
        for i in range(1, int(added_num / 2) + 1):
            if added_num > 1:
                added_num_price_list.append(average_price - i * max_times)
                added_num -= 1
            if added_num > 1:
                added_num_price_list.append(average_price + i * max_times)
                added_num -= 1
        added_num_price_list.sort()

    for i in added_num_price_list:
        if price_dict.get(i):
            price_dict[i] += 1
        else:
            price_dict[i] = 1

    total = 0
    for price, num in price_dict.items():
        total += price * num
    if total < total_price*ratio:
        free_money = abs(int(total - total_price*ratio))
        s_price, s_num = sorted(price_dict.items())[0]
        if price_dict.get(s_price + free_money):
            price_dict[s_price + free_money] += 1
        else:
            price_dict[s_price + free_money] = 1

        if s_num == 1:
            price_dict.pop(s_price)
        else:
            price_dict[s_price] -= 1

    s_list = list()
    for price, num in sorted(price_dict.items()):
        s_list.append("{}:{}".format(price, num))
    return s_list


def hanging_order_list(goods_id, d_type, r_type):
    hanging_order = HangingOrder.query.filter_by(
        status=0, goods_id=goods_id, r_type=r_type
    ).order_by(HangingOrder.create_time.desc()).limit(10)
    order_list = list()
    for i in hanging_order:
        order_info = {'surplus_num': i.surplus_num}
        order_list.append(order_info)
    return order_list


def batch_type_str(r_type, d_type):     # r_type 1可提  2待释放  3可卖
    status_str = ''
    if r_type == 1:
        if d_type == 1:
            status_str = '批发买入'
        elif d_type == 2:
            status_str = '拍品过期'
    elif r_type == 2:
        if d_type == 1:
            status_str = ''
        elif d_type == 2:
            status_str = '特价购买'
    elif r_type == 3:
        if d_type is None:
            status_str = '系统配送'
        elif d_type == 1:
            status_str = '批发买入'
        elif d_type == 2:
            status_str = '释放拍品'
    return status_str



